main.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """Primary application entrypoint.
  2. """
  3. from __future__ import absolute_import
  4. import locale
  5. import logging
  6. import os
  7. import sys
  8. from pip._internal.cli.autocompletion import autocomplete
  9. from pip._internal.cli.main_parser import parse_command
  10. from pip._internal.commands import create_command
  11. from pip._internal.exceptions import PipError
  12. from pip._internal.utils import deprecation
  13. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  14. if MYPY_CHECK_RUNNING:
  15. from typing import List, Optional
  16. logger = logging.getLogger(__name__)
  17. # Do not import and use main() directly! Using it directly is actively
  18. # discouraged by pip's maintainers. The name, location and behavior of
  19. # this function is subject to change, so calling it directly is not
  20. # portable across different pip versions.
  21. # In addition, running pip in-process is unsupported and unsafe. This is
  22. # elaborated in detail at
  23. # https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
  24. # That document also provides suggestions that should work for nearly
  25. # all users that are considering importing and using main() directly.
  26. # However, we know that certain users will still want to invoke pip
  27. # in-process. If you understand and accept the implications of using pip
  28. # in an unsupported manner, the best approach is to use runpy to avoid
  29. # depending on the exact location of this entry point.
  30. # The following example shows how to use runpy to invoke pip in that
  31. # case:
  32. #
  33. # sys.argv = ["pip", your, args, here]
  34. # runpy.run_module("pip", run_name="__main__")
  35. #
  36. # Note that this will exit the process after running, unlike a direct
  37. # call to main. As it is not safe to do any processing after calling
  38. # main, this should not be an issue in practice.
  39. def main(args=None):
  40. # type: (Optional[List[str]]) -> int
  41. if args is None:
  42. args = sys.argv[1:]
  43. # Configure our deprecation warnings to be sent through loggers
  44. deprecation.install_warning_logger()
  45. autocomplete()
  46. try:
  47. cmd_name, cmd_args = parse_command(args)
  48. except PipError as exc:
  49. sys.stderr.write("ERROR: {}".format(exc))
  50. sys.stderr.write(os.linesep)
  51. sys.exit(1)
  52. # Needed for locale.getpreferredencoding(False) to work
  53. # in pip._internal.utils.encoding.auto_decode
  54. try:
  55. locale.setlocale(locale.LC_ALL, '')
  56. except locale.Error as e:
  57. # setlocale can apparently crash if locale are uninitialized
  58. logger.debug("Ignoring error %s when setting locale", e)
  59. command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
  60. return command.main(cmd_args)